package com.dm.cloud.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.dm.cloud.common.R;
import com.dm.cloud.dao.TestDao;
import com.dm.cloud.service.ITestService;
import com.dm.cloud.utils.distributedlock.RedisDSLock;
import com.dm.cloud.utils.distributedlock.ZookeeperDSLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.TimeUnit;

//@Slf4j
@Service
public class TestServiceImpl implements ITestService {

    @Override
    public boolean redisLock() {
        return RedisDSLock.tryLock("key","value");
    }

    @Override
    public boolean zkLock(Integer inr ) {

        ZookeeperDSLock zookeeperDSLock= new ZookeeperDSLock.Builder().build();
        if( zookeeperDSLock.lock("testLock")){
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(3000);
                }catch (Exception ex){
//                    log.error(ex.getMessage());
                }
                zookeeperDSLock.unlock("testLock");
            }).start();
            System.out.println(inr+" locked"  );
            return true;
        }else{
            System.out.println(inr+" lock error"  );
        }

//        SimpleDateFormat sf=new SimpleDateFormat("yyyy-dd-MM HH:mm:ss:SSS");
//        try {
//            zookeeperDSLock.doOnWaitLock("locktest",()->{
//                String time =sf.format(new Date());
//                System.out.println(inr+" "+time+" i am doing work");
//                try {
//                    TimeUnit.MILLISECONDS.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });
//
//        }catch (Exception ex){
//            log.error(ex.getMessage());
//        }
        //执行操作
        return true;
    }


    @Autowired
    TestDao testDao;

    @Override
    @DS("slave")
    public R<Object> multiDbTest(String sds, String sdsdsds, String db) {
        try {
            List<String> tableName = testDao.getCurrentDbTable();
            return R.success(tableName);
        }catch (Exception ex){
            return R.failure("500",ex.getMessage());
        }
    }

    @Override
    public R<Object> minioUploud(MultipartFile file) {
        return null;
    }

    @Override
    @Transactional(label = "trans")
    public void transTerst2() {
        testDao.insertTest("5");
        testDao.insertTest("6");
    }
}
